package cn.buglife.concurrent.exchanger;

import java.util.concurrent.Exchanger;

/**
 * Exchanger 类表示一种两个线程可以进行互相交换对象的会和点。
 *
 * @author zhangjun
 */
public class ExchangerSample {

  public static void main(String[] args) {
    Exchanger<String> exchanger = new Exchanger<> ();

    String param1 = "hello";
    String param2 = "world";

    new Thread ( test ( exchanger, param1 ) ).start ();
    new Thread ( test ( exchanger, param2 ) ).start ();
  }

  private static Runnable test(Exchanger<String> exchanger, String param) {
    return () -> {
      String previous = null;
      try {
        // 交换对象的动作由 Exchanger 的两个 exchange() 方法的其中一个完成。
        previous = String.valueOf ( exchanger.exchange ( param ) );
      } catch (InterruptedException e) {
        e.printStackTrace ();
      }
      System.out
              .println ( Thread.currentThread ().getName () + " exchanged " + previous + " for " + param );
    };
  }
}
